<template>
    <div class='categoryClass'>
      <div>
        <div class='content-title'>
          <div class='content-title-parent'>系统管理</div>
          /
          <div class='content-title-child'>账户管理</div>
        </div>
        <hr class='content-hr'/>
      </div>
      <el-row style="margin-top:10px">
        <el-button type="warning" style="float:right;margin-right:20px" @click="addVisable = true">添加</el-button>
      </el-row>
      <!--表格数据-->
      <el-row style="margin-top:10px">
        <el-table
          v-loading="loading"
          :element-loading-text="loadingText"
          element-loading-spinner="el-icon-loading"
          :data="filterFormFro.tableData" 
          :border="true" 
          :row-class-name="tableRowClassName"
          :header-cell-class-name = "tableHeaderClassName"
          v-bind:style="{width: tableWidth + 'px'}">
            <el-table-column prop="adminName" label="账户" min-width="10%">
            </el-table-column>
            <el-table-column prop="position" label="职位" min-width="20%">
            </el-table-column>
            <el-table-column prop="roleName" label="角色" min-width="20%">
            </el-table-column>
            <el-table-column prop="updateTime" label="更新日期" min-width="20%">
            </el-table-column>
            <el-table-column label="操作" min-width="30%">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  @click="handleDelete(scope.$index, scope.row)">删除</el-button>
              </template>
            </el-table-column>
        </el-table>
      </el-row>
      <!-- 表格下方分页 -->
      <el-row>
        <div style='text-align:center;clear:both'>
          <div class="pagination" style="text-align:center" v-show="paginationVisible">
              <el-pagination
                @current-change="handleCurrentChange"
                background
                :current-page="filterForm.currentPage"
                :page-size="15"
                layout="total, prev, pager, next"
                :page-count="filterFormFro.totalPage">
              </el-pagination>
          </div>
        </div>
      </el-row>
      <!-- 添加账户信息弹窗 -->
      <el-dialog title="增加账户:"   :visible.sync="addVisable"
          :closeOnClickModal="false"
          width="550px"
          class="categoryManaDialog"
          :close-on-click-modal="false" 
          :close-on-press-escape="false"
          @close="resetForm('addForm')">
        <el-form :model='addForm' ref="addForm" :rules="addrules" label-width="170px">
            <el-form-item label="账户名：" prop="adminName">
              <el-input style='width:240px' @keyup.native="addForm.adminName=addForm.adminName.replace(/[^\w\u4e00-\u9fa5\s]/g, '')" v-model.trim="addForm.adminName" type="text" ></el-input>
            </el-form-item>
            <el-form-item label="职位："  prop="position">
              <el-input style='width:240px' @keyup.native="addForm.position=addForm.position.replace(/[^\w\u4e00-\u9fa5\s]/g, '')"  v-model.trim="addForm.position" type="text"></el-input>
            </el-form-item>
            <el-form-item label="密码："  prop="password">
              <el-input style='width:240px' @keyup.native="addForm.password=addForm.password.replace(/[^\w]/g, '')"  v-model="addForm.password" type="password" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="确认密码："  prop="passwordAgain">
              <el-input style='width:240px' @keyup.native="addForm.passwordAgain=addForm.passwordAgain.replace(/[^\w]/g, '')"    v-model="addForm.passwordAgain" type="password" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="角色："  prop="roleId">
              <el-select v-model="addForm.roleId" style="width:240px" clearable placeholder="请选择">
                  <el-option
                      v-for="item in roleList"
                      :label="item.roleName"
                      :key="item.roleId"
                      :value="item.roleId">
                  </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="">
              <el-button type="primary" style="width:240px"  @click="submitAdd()">提 交</el-button>
            </el-form-item>
        </el-form>
      </el-dialog>
      <!-- 编辑账户信息弹窗 -->
      <el-dialog title="编辑账户信息:"   :visible.sync="editVisable"
        :closeOnClickModal="false" 
        width="550px"
        class="categoryManaDialog"
        :close-on-click-modal="false" 
        :close-on-press-escape="false"
        @close="resetForm('editForm')">
        <el-form :model='editForm' :rules="editrules" ref="editForm" label-width="170px">
            <el-form-item label="账户名：" prop="adminName">
              <el-input style='width:240px' :disabled="true" @keyup.native="editForm.adminName=editForm.adminName.replace(/[^\w\u4e00-\u9fa5\s]/g, '')"  v-model.trim="editForm.adminName" type="text" ></el-input>
            </el-form-item>
            <el-form-item label="职位："  prop="position">
              <el-input style='width:240px' @keyup.native="editForm.position=editForm.position.replace(/[^\w\u4e00-\u9fa5\s]/g, '')"  v-model.trim="editForm.position" type="text"></el-input>
            </el-form-item>
            <el-form-item label="密码："  prop="password">
              <el-input style='width:240px' @keyup.native="editForm.password=editForm.password.replace(/[^\w]/g, '')"  v-model="editForm.password" type="password" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="确认密码："  prop="passwordAgain">
              <el-input style='width:240px' @keyup.native="editForm.passwordAgain=editForm.passwordAgain.replace(/[^\w]/g, '')" v-model="editForm.passwordAgain" type="password" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="角色："  prop="roleId">
              <el-select v-model="editForm.roleId" style="width:240px" clearable placeholder="请选择">
                  <el-option
                      v-for="item in roleList"
                      :label="item.roleName"
                      :key="item.roleId"
                      :value="item.roleId">
                  </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="">
              <el-button type="primary" style="width:240px"  @click="submitEdit()">提 交</el-button>
            </el-form-item>
        </el-form>
      </el-dialog>
    </div>
</template>
<script>
import apiBus from '../../api/businessPlat/apiBus.js'
import md5 from 'js-md5'
import '../../../static/css/businessPlat/common.css'
import '../../../static/css/businessPlat/categoryMana.css'
export default {
  created () {
    this.getAllRoleFro()
    this.getAccountListFro()
  },
  data () {
    // 密码过滤特殊字符串
    /* var checkPassword = (rule, value, callback) => {
      value = value.replace(/[^\w]/g, '')
      callback()
    } */
    // 普通输入框过滤特殊字符串
    /* var checkString = (rule, value, callback) => {
      value = value.replace(/[^\w\u4e00-\u9fa5\s]/g, '')
      callback()
    } */
    // 增加表单中的第一次密码验证
    var addvalidatePass = (rule, value, callback) => {
      if (this.addForm.passwordAgain !== '') {
        this.$refs.addForm.validateField('passwordAgain')
      }
      callback()
    }
    // 增加表单中的第二次密码验证
    var addvalidatePass2 = (rule, value, callback) => {
      if (value !== this.addForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    // 编辑表单中的第一次密码验证
    var editvalidatePass = (rule, value, callback) => {
      if (this.editForm.passwordAgain.trim() !== '') {
        this.$refs.editForm.validateField('passwordAgain')
      }
      callback()
    }
    // 编辑表单中的第二次密码验证
    var editvalidatePass2 = (rule, value, callback) => {
      if (value.trim() === '') {
        this.editForm.passwordAgain = ''
      }
      if (value.trim() !== this.editForm.password.trim()) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      tableWidth: '',
      testData: [],
      testData2: [],
      paginationVisible: false, // 表格下方的分页显示
      pointVisible: false, // 后台请求数据提示是否显示
      Note: '', // 后台请求数据提示
      loading: false, // 表格数据加载框
      loadingText: '正在拼命加载中，请稍等......',
      noteVisible: false,
      formLabelWidth: '30%',
      addForm: {
        adminName: '', // 账户
        position: '', // 职位
        roleName: '', // 角色
        roleId: '',
        password: '',
        passwordAgain: ''
      },
      roleList: ['编辑', '主管', '主编', '管理员'], // 账户角色列表
      addVisable: false,
      filterForm: {
        currentPage: 1, // 当前页数
        pageSize: 10 // 页面大小
      },
      filterFormFro: {
        tableData: [],
        totalPage: 30 // 总共页数
      },
      editVisable: false,
      editForm: {
        adminId: '', // 账户ID
        adminName: '', // 账户
        position: '', // 职位
        roleId: '', // 角色
        password: '',
        passwordAgain: '',
        originpassword: '',
        originpasswordAgain: ''
      },
      deleteForm: {
        adminName: '', // 账户名称
        adminId: '' // 账户ID
      },
      editrules: {
        adminName: [
          { required: true, message: '请输入账户名', trigger: 'blur' },
          { max: 20, message: '账户名最多20个字符', trigger: 'blur' }
        ],
        position: [
          { required: true, message: '请输入职位', trigger: 'blur' },
          { max: 10, message: '职位最多10个字符', trigger: 'blur' }
        ],
        password: [
          /* { required: true, message: '请输入密码', trigger: 'blur' }, */
          { validator: editvalidatePass, trigger: 'blur' },
          { max: 10, message: '密码最多10个字符', trigger: 'blur' }
        ],
        passwordAgain: [
          // { required: true, message: '请再次输入密码', trigger: 'blur' },
          { validator: editvalidatePass2, trigger: 'blur' },
          { max: 10, message: '确认密码最多10个字符', trigger: 'blur' }
        ],
        roleId: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ]
      },
      addrules: {
        adminName: [
          { required: true, message: '请输入账户名', trigger: 'blur' },
          { max: 20, message: '账户名最多20个字符', trigger: 'blur' }
        ],
        position: [
          { required: true, message: '请输入职位', trigger: 'blur' },
          { max: 10, message: '职位最多10个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { validator: addvalidatePass, trigger: 'blur' },
          { max: 10, message: '密码最多10个字符', trigger: 'blur' }
        ],
        passwordAgain: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          { validator: addvalidatePass2, trigger: 'blur' },
          { max: 10, message: '确认密码最多10个字符', trigger: 'blur' }
        ],
        roleId: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ]
      }
    }
  },
  methods: {
    // 将时间转化为字符串
    formatDateFro: function (now) {
      var year = now.getFullYear()
      var month = now.getMonth() + 1
      month = month < 10 ? '0' + month : month
      var date = now.getDate()
      date = date < 10 ? ('0' + date) : date
      var hour = now.getHours()
      hour = hour < 10 ? ('0' + hour) : hour
      var minute = now.getMinutes()
      minute = minute < 10 ? ('0' + minute) : minute
      var second = now.getSeconds()
      second = second < 10 ? ('0' + second) : second
      return year + '-' + month + '-' + date + ' ' + hour + ':' + minute + ':' + second
    },
    // 重置表单
    resetForm (formName) {
      this.$nextTick(function () {
        this.$refs[formName].resetFields()
      })
    },
    // 增加账户，点击“保存”
    submitAdd () {
      this.$refs['addForm'].validate((valid) => {
        if (valid) {
          this.addAccountListFro()
        } else {
          return false
        }
      })
    },
    // 编辑账户，点击“保存”
    submitEdit () {
      this.$refs['editForm'].validate((valid) => {
        if (valid) {
          this.editAccountListFro()
        } else {
          return false
        }
      })
    },
    /** 提交后台相关函数 */
    // 查询下拉菜单的所有角色列表
    getAllRoleFro () {
      let para = {
        header: JSON.stringify({
          token: sessionStorage.getItem('token')
        }),
        body: JSON.stringify({})
      }
      apiBus.getAllRole(para).then(res => {
        this.roleList = []
        if (res.data.body.result === 1000) {
          this.roleList = res.data.body.content.list
        } else {
          this.$message.error(res.data.body.resultDesp)
        }
      })
      .catch(error => {
        this.$message.error(error)
      })
    },
    // 向后台查看账户列表
    getAccountListFro () {
      this.loading = true
      this.paginationVisible = false
      let para = {
        header: JSON.stringify({
          token: sessionStorage.getItem('token')
        }),
        body: JSON.stringify({
          pageNum: parseInt(this.filterForm.currentPage) // 当前页面数
        })
      }
      console.log('getAccountList入参：')
      console.log(para)
      apiBus.getAccountList(para).then(res => {
        console.log('getAccountList回参')
        console.log(res)
        this.loading = false
        if (res.data.body.result === 1000) {
          let resData = res.data.body.content.list
          if (resData.length > 0) {
            this.$message.success('获取账户信息成功！')
            this.filterFormFro.tableData = resData
            this.filterFormFro.pageNum = parseInt(res.data.body.content.pageNum)
            for (let i = 0; i < resData.length; i++) {
              this.filterFormFro.tableData[i].index = (parseInt(this.filterForm.currentPage) - 1) * 15 + (i + 1)
              this.filterFormFro.tableData[i].updateTime = this.formatDateFro(new Date(resData[i].updateTime))
            }
            this.filterFormFro.totalPage = res.data.body.content.allPages
            this.filterFormFro.totalPage > 1 ? this.paginationVisible = true : this.paginationVisible = false
          } else {
            this.$message.warning('没有任何账户信息')
          }
        } else {
          this.$message.error(res.data.body.resultDesp)
        }
      })
      .catch(error => {
        this.loading = false
        this.$message.error(error)
      })
    },
    // 向后台增加账户信息
    addAccountListFro () {
      let para = {
        header: JSON.stringify({
          token: sessionStorage.getItem('token')
        }),
        body: JSON.stringify({
          roleId: parseInt(this.addForm.roleId),
          adminName: this.addForm.adminName,
          position: this.addForm.position,
          roleName: this.addForm.roleName,
          password: md5(this.addForm.password)
        })
      }
      console.log('addAccountList入参：')
      console.log(para)
      apiBus.addAccountList(para).then(res => {
        console.log('addAccountList回参')
        console.log(res)
        if (res.data.body.result === 1000) {
          this.filterForm.currentPage = 1
          this.getAccountListFro()
          this.$message.success('增加账户成功！')
          this.addVisable = false
        } else {
          this.$message.warning(res.data.body.resultDesp)
        }
      })
      .catch(error => {
        this.addVisable = false
        this.$message.error(error)
      })
    },
    // 向后台编辑账户
    editAccountListFro () {
      let password = ''
      if (this.editForm.password.trim() === '') {
        password = this.editForm.originpassword
      } else {
        password = md5(this.editForm.password)
      }
      console.log(password)
      let para = {
        header: JSON.stringify({
          token: sessionStorage.getItem('token')
        }),
        body: JSON.stringify({
          adminId: parseInt(this.editForm.adminId),
          adminName: this.editForm.adminName,
          position: this.editForm.position,
          roleId: parseInt(this.editForm.roleId),
          password: password
        })
      }
      console.log('editAccountListFro')
      console.log(para)
      apiBus.editAccountList(para).then(res => {
        console.log('回参')
        console.log(res)
        if (res.data.body.result === 1000) {
          this.filterForm.currentPage = 1
          this.$message.success('编辑账户成功！')
          this.getAccountListFro()
          this.editVisable = false
        } else {
          this.$message.warning(res.data.body.resultDesp)
        }
      })
      .catch(error => {
        this.editVisable = false
        this.$message.error(error)
      })
    },
    // 向后台删除账户
    deleteAccountListFro () {
      let para = {
        header: JSON.stringify({
          token: sessionStorage.getItem('token')
        }),
        body: JSON.stringify({
          adminId: parseInt(this.deleteForm.adminId)
        })
      }
      apiBus.deleteAccountList(para).then(res => {
        if (res.data.body.result === 1000) {
          this.filterForm.currentPage = 1
          this.getAccountListFro()
          this.$message.success('成功删除该账户')
        } else {
          this.$message.error(res.data.body.resultDesp)
        }
      })
      .catch(error => {
        this.$message.error(error)
      })
    },
    // 分页页面跳转时
    handleCurrentChange (val) {
      this.filterForm.currentPage = val
      this.getAccountListFro()
    },
    tableHeaderClassName ({row, column, rowIndex, columnIndex}) {
      if (rowIndex === 0) {
        return 'headerClass'
      }
    },
    tableRowClassName ({row, rowIndex}) {
      return 'rowClass'
    },
    // 表格中点击编辑按钮弹出点击弹窗口，补充数据
    handleEdit (index, row) {
      let data = this.filterFormFro.tableData[index]
      this.editForm.adminId = index
      this.editForm.adminName = data.adminName
      this.editForm.adminId = data.adminId
      this.editForm.position = data.position
      this.editForm.roleId = data.roleId
      this.editForm.password = ''
      this.editForm.passwordAgain = ''
      this.editForm.originpassword = data.password
      this.editForm.originpasswordAgain = data.password
      this.editVisable = true
      console.log('hanldeEdit')
      console.log(data)
    },
    // 点击表格中的删除按钮
    handleDelete (index, row) {
      this.deleteForm.adminId = this.filterFormFro.tableData[index].adminId
      this.$confirm('确定删除该账户吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteAccountListFro()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    cancleEdit (formName) {
      this.resetError(formName)
      this.editVisable = false
    },
    // 重置表单
    resetError (formName) {
      this.$nextTick(function () {
        this.$refs[formName].resetFields()
      })
    }
  },
  mounted () {
    this.tableWidth = document.body.scrollWidth - 259 - 20
  }
}
</script>